package com.ceo.auth.jwt.handler;

import cn.hutool.core.util.StrUtil;
import com.ceo.auth.jwt.JwtEntity;
import com.ceo.auth.jwt.JwtUtil;
import com.ceo.auth.jwt.chain.CallableChain;
import com.ceo.auth.jwt.wrapper.JwtWrapper;
import com.ceo.common.threadlocal.EnvironCons;
import com.ceo.common.threadlocal.GlobalMemcache;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Supplier;

/**
 * @Create by hefy
 * @Date 2022/1/13 10:01
 * 身份验证
 */
@Component
public class JwtAuthenticationHandler extends AbstractJwtHandler<JwtWrapper> {


    @Override
    public Boolean doHandle(CallableChain<Boolean, JwtWrapper> chain, Supplier<JwtWrapper> supplier) throws Exception {

        HttpServletRequest httpServletRequest = supplier.get().getRequest();

        String token = httpServletRequest.getHeader("Authorization");

        if (!checkRequestAuth(token, supplier)) {
            return Boolean.FALSE;
        }

        GlobalMemcache.setL(EnvironCons.TOKEN, token);

        return chain.doProceed(supplier);
    }


    private boolean checkRequestAuth(String token, Supplier<JwtWrapper> supplier) {

        if (StrUtil.isBlank(token) || !JwtUtil.verify(token = token.replaceFirst("Bearer ", ""))) {
            return supplier.get().responseState(401);
        }
        //验证通过，黑名单校验
        JwtEntity jwtEntity = JwtUtil.getJWTEntity(token);
        supplier.get().setJwtEntity(jwtEntity);
        return Boolean.TRUE;
    }
}
